﻿
<!DOCTYPE html>
<html>
<head>
	<title>问卷答题</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<link rel="stylesheet" type="text/css" href="/framework/vue/weui.min.css">
<link rel="stylesheet" type="text/css" href="/system/views/wenjuan/wenjuan.css">
<style>
.tab { border:1px #cccccc solid; border-collapse:collapse; width:100%; }
.tab td { border:1px #cccccc solid; height:18px; line-height:18px; padding:3px; padding-left:10px; }
.tab th { border:1px #cccccc solid; height:18px; line-height:18px; padding:3px; padding-left:10px; }
li {
    padding: 0.5rem;
    border-top: 1px solid #eee;
}
li:hover {
    background-color: #eee;
}
ul
{
    border: 1px solid #eee;
        margin-top: 2rem;
    border-top: 0;
}
</style>
</head>
<body>

<div id="app" style="padding: 0" >
<div class="container" style=" overflow:hidden;">
<h1>{{wjobj.title}}统计</h1>
<br />
<br />
<br />
<h4 style="text-align:center;">参与人：<strong style="font-size:24px;">{{totleInfo.userid}}</strong>个，<span v-if="totleInfo.totalNumber!=0">完成度：<strong style="font-size:24px;">{{(totleInfo.totalNumber==0)?0:((totleInfo.userid/totleInfo.totalNumber)*100).toFixed(2)}}</strong>%，</span>总平均分：<strong style="color:#39f;font-size:24px;">{{totleInfo.score}}</strong>分</h4>
<br />
<br />
<br />
<div v-for="(groupobj,index) in wjobj.question" :key="groupobj.id" style=" overflow:hidden;"><!--遍历题题目分组-->
	<div class="weui-loadmore weui-loadmore_line">
	            <span class="weui-loadmore__tips">{{groupobj.groupname}}</span>
	</div>
    <!--这里是以组为单位，量表题-->
   <div :id="'echart_'+groupobj.id" style="float:left;width:49%; height:400px; margin-top:20px;"></div>
   <!--这里是题为单位，单选或多选题-->
   <div v-for="(questionobj,xuhao) in groupobj.group" v-if="questionobj.qtype == 0||questionobj.qtype == 1" :id="'echart_'+questionobj.id" style="float:left;width:49%; height:400px; margin-top:20px;"></div>

            <div v-for="(questionobj,xuhao) in groupobj.group"  v-if="questionobj.qtype == 2" style=" margin-top:20px;" >
           【问答题】 {{questionobj.qtitle}}<br/>
           <ul  v-if="questionobj.datas" >
                <li  v-for="(answer,index) in questionobj.datas"><strong>{{index+1}}、</strong>{{answer.answer}}</li>
           </ul>
           <a href="javascript:void(0);" @click="loadMore(index,xuhao)" v-if="questionobj.datas.length<questionobj.numCount" class="weui-btn weui-btn_mini weui-btn_default">加载更多</a>
      <a href="javascript:void(0);" @click="findAnswer(index,xuhao)" v-if="!questionobj.show" class="weui-btn weui-btn_mini weui-btn_default">查看答案</a>
      </div>
</div>
<!-- loading toast -->
    <div id="loadingToast" v-if="loading">
        <div class="weui-mask_transparent"></div>
        <div class="weui-toast">
            <i class="weui-loading weui-icon_toast"></i>
            <p class="weui-toast__content">数据加载中</p>
        </div>
    </div>
</div>
</div>
<div class="weui-footer">
            <p class="weui-footer__text">Copyright © </p>
        </div>
<div id="laod" style="position: fixed; top:0;left: 0; width: 100%; height: 100%; background-color: #eee; text-align: center; padding-top: 100px;">
	<i class="weui-loading weui-icon_toast"></i><br>
	正在统计数据，请稍候
</div>


<script src="/framework/angular.min.js"></script>
<script type="text/javascript" src="/framework/vue/zepto.min.js"></script>
<script src="/framework/lodash.min.js" type="text/javascript"></script>
<script src="/framework/echarts/echarts.min.js" type="text/javascript"></script>
<script src="/framework/restangular/restangular.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/framework/angular-toastr/angular-toastr.min.js"></script>
<script type="text/javascript" src="/framework/angular-toastr/angular-toastr.tpls.min.js"></script>
    <script src="/framework/angular-wang-editor/dist/js/lib/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="/framework/vue/vue.min.js" type="text/javascript" ></script>
<script src="/system/service/common.js" type="text/javascript"></script>    
<script type="text/javascript">
var yuming ="";
try{
yuming = commonUrl;
}catch(e){
alert("ee");
}

var wenjuan ={};
var echartList=[];
var dati =[];
var user = {};//登录人信息，注意需要企业ID,组织架构ID
var vm;

var totleInfo={};
var key = QueryString("key");
var xtype = QueryString("xtype");
var xid = QueryString("xid");
var type = QueryString("type");
var pageIndex=1;
//界面初始化
$(function(){
	 var key = QueryString("key");
  if(key != null){
    user = GetlocalStorage("userinfo");
    //获取统计信息
    getAjax(yuming+"/questionnaire/questionnaireDetails",{qid:key,xtype:xtype,xid:xid},function(data){
      if(data.errorcode == "0"){
        totleInfo=data.data;
      }
      else{
        alert("读取错误"+data.errorcode);
      }
        getAjax(yuming+"/questionnaire/findTopicDetails",{qid:key,xtype:xtype,xid:xid,type:type},function(data){
      if(data.errorcode == "0"){
        wenjuan = data.data;
        echartList=JSON.parse(data.data.question);
        wenjuan.question = JSON.parse(data.data.question);
        //初始问答题的分页信息
        for(var i =0;i<wenjuan.question.length;i++){
            for(var j =0;j<wenjuan.question[i].group.length;j++){
                if(wenjuan.question[i].group[j].qtype==2){
                    wenjuan.question[i].group[j].pageIndex=1;
                    wenjuan.question[i].group[j].numCount=0;
                    wenjuan.question[i].group[j].nowCount=0
                    wenjuan.question[i].group[j].datas=[];
                    wenjuan.question[i].group[j].show=false;
                }
            }
        }
       //wenjuan.qualified = JSON.parse(data.data.qualified);
        wenjuan.taglist = JSON.parse(data.data.taglist);
        wenjuan.result = JSON.parse(data.data.result);
        console.log(wenjuan);

        if(!wenjuan.login && user == null)//如果不能匿名，且未登录
        {
          window.location = "/index.html";
        }
        else{
          vmchushi();
          if(QueryString("b") != null){
            vm.baobiao = true;
          }
          $("#laod").hide();
          makingEchart();
        }
      }
      else{
        alert("读取错误"+data.errorcode);
      }
    });   
    
    });   
   /******************************************************************/
  }
  else{
    alert("参数错误");
  }

});
  //***************************************************************开始绘图********************************************************/
  function makingEchart(){
   echartList.forEach(function(data,index){
         
         //存放角的数量
         var nameList=[];
         //存放值
         var valueList=[];
         var d_count=0;//单选的数量
         var lb_count=0;//量表题数量
         var wd_count=0;//问答的数量
         data.group.forEach(function(data2,index2){
            if(data2.qtype!=2){
                //统计占比
                if(data2.qtype==0||data2.qtype==1){
                    d_count=d_count+1;
                }else if(data2.qtype==3||data2.qtype==4){
                    lb_count=lb_count+1;
                }else{
                    wd_count=wd_count+1;
                }
            }
         });
         //移除量表题空白
         if(lb_count<=0){
            $("#echart_"+data.id).remove();  
         }
         //移除单选多选空白
         if(d_count<=0){
            data.group.forEach(function(data2,index2){
                     $("#echart_"+data2.id).remove();  
            });
           if(lb_count>0){
                var a=document.getElementById("echart_"+data.id);
                a.style.width="100%";
            }
         }
        var option=null;
        //单选或多选（饼状图）
        if(d_count>0){
                //$(".lbt").remove();
               //便利题
                data.group.forEach(function(data2,index2){
						var tabhtml = "";
                        nameList=[];
                        valueList=[];
                        //统计占比
                        if(data2.qtype==0||data2.qtype==1){
                            var dom = document.getElementById("echart_"+data2.id);
                            var myChart = echarts.init(dom);
							
                            //遍历选项
                            data2.qselection.forEach(function(data3,index3){
                                nameList.push(data3.text);
                                 //选择的数量
                                 valueList.push({value:data3.selected,name:data3.text});
                                 tabhtml += "<tr><td>"+data3.text+"</td><td>"+data3.selected+"</td></tr>";
                            });
                            option = {
                            title : {
                                text: data2.qtitle,
                                subtext: data2.qtype==0?"单选":"多选",
                                x:'left'
                            },
                            tooltip : {
                                trigger: 'item',
                                formatter: "{a} <br/>{b} : {c} ({d}%)"
                            },
                            legend: {
                                x : 'center',
                                y : 'bottom',
                                data: nameList
                            },
                            series : [
                                {
                                    name: '访问来源',
                                    type: 'pie',
                                    radius : '55%',
                                    center: ['50%', '50%'],
                                    data:valueList,
                                    itemStyle: {
                                        emphasis: {
                                            shadowBlur: 10,
                                            shadowOffsetX: 0,
                                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                                        }
                                    }
                                }
                            ]
                        };
                            if (option && typeof option === "object") {
                                myChart.setOption(option, true);
                            }
							$("#echart_"+data2.id).after("<div style=\"float: left; width: 49%; height: 400px; margin-top: 20px; -webkit-tap-highlight-color: transparent; user-select: none; position: relative; background: transparent;\"><table class='tab'><tr><th>项目</th><th>选择次数</th></tr>"+tabhtml+"</table></div>");
                        }
                 });
        
         }

        //量表（多角图+柱形图）
        if(lb_count>0){


         
        //这是柱形图
        var dom = document.getElementById("echart_"+data.id);
             var myChart = echarts.init(dom);
                 //遍历选项
                data.group.forEach(function(data2,index2){
                     if(data2.qtype==3||data2.qtype==4){
                         nameList.push(data2.qtitle);
                        //随机数
                        valueList.push(data2.qselection[0].score);
                    }
                });
            //$(".dx").remove();
             option = {
                    xAxis: {
                        type: 'category',
                        data: nameList
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [{
                        data: valueList,
                        type: 'bar'
                    }]
                };
            if (option && typeof option === "object") {
                myChart.setOption(option, true);
            }


        }




    }); 
  }
  

 //***************************************************************绘图结束********************************************************/
function vmchushi(){
	vm = new Vue({
		el: '#app',
  		data: {
  			wjobj:wenjuan,//题目对象
  			answer:dati, //答题记录
            totleInfo:totleInfo,//答题统计
  			loading:false,
  		},
  		methods: {
        jindutiao:function(sel,qid){
        },
        tixingname:function(typeid){
  				if(typeid == 0)
  				{
  					return "单选题";
  				}
  				else if(typeid == 1)
  				{
  					return "多选题";
  				}
  				else if(typeid == 2)
  				{
  					return "问答题";
  				}
  				else if(typeid == 3)
  				{
  					return "量表题";
  				}
  				else if(typeid == 4)
  				{
  					return "打分题";
  				}
  				else{
  					console.log(typeid);
  					return "未知";
  				}
  			},
            findAnswer:function(id1,id2){
            var alist= this.wjobj.question;
                var canshu={
                    qid:key,
                    xid:xid,
                    xtype:xtype,
                    tid:alist[id1].group[id2].id,
                    pageIndex:pageIndex,
                    pageSize:20
                };
                getAjax(yuming+"/questionnaire/findAnswerPage",canshu,function(data){
					if(data.errorcode == "0"){
                        alist[id1].group[id2].datas=data.datas;
                        alist[id1].group[id2].show=true;
                        alist[id1].group[id2].nowCount=data.datas.length;
                        alist[id1].group[id2].pageIndex=data.pageIndex;
                        alist[id1].group[id2].numCount=data.numCount;
			  		}else{
						alert("错误"+data.errorcode);
					}
				});
            },
             loadMore:function(id1,id2){
             var alist= this.wjobj.question;
                var canshu={
                    qid:key,
                    xid:xid,
                    xtype:xtype,
                    tid:alist[id1].group[id2].id,
                    pageIndex:alist[id1].group[id2].pageIndex+1,
                    pageSize:20
                };
                getAjax(yuming+"/questionnaire/findAnswerPage",canshu,function(data){
					if(data.errorcode == "0"){
                        alist[id1].group[id2].datas=alist[id1].group[id2].datas.concat(data.datas);
                        alist[id1].group[id2].nowCount=data.datas.length;
                        alist[id1].group[id2].pageIndex=data.pageIndex;
                        alist[id1].group[id2].numCount=data.numCount;
			  		}else{
						alert("错误"+data.errorcode);
					}
				});
            }
  		},//注册函数
  		directives:{//注册指令
  			
  		}
	});
}

//用于生成uuid
function guid() {
	function S4() {
	    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	}
	 return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
/**
  *工具 || 获得URL GET参数
 */
function QueryString(fieldName) {
    /// <summary>
    ///   获得URL GET参数
    /// </summary>
    /// <param name="fieldName" type="String">
    ///   参数名
    /// </param>
    /// <returns type="void" />如果不存在返回NULL
    var reg = new RegExp("(^|&)" + fieldName.toLowerCase() + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
//**********************************************************************
//全局异步请求数据
//**********************************************************************
document.writeln("<div id=\'loadingToast\' style=\'display:none;\'>");
document.writeln("        <div class=\'weui-mask_transparent\'></div>");
document.writeln("        <div class=\'weui-toast\'>");
document.writeln("            <i class=\'weui-loading weui-icon_toast\'></i>");
document.writeln("            <p class=\'weui-toast__content\'>数据加载中</p>");
document.writeln("        </div>");
document.writeln("    </div>");
function getAjax(url, parm, callBack, callBackError, callBackType, mode, istongbu) {
    $("#loadingToast").show();
    var token = "userinfo_token is none";
    if (callBackType == null || callBackType == "" || callBackType == undefined)
        callBackType = "text";
    if (mode == null || mode == "" || mode == undefined)
        mode = "post";
    if (istongbu != undefined && !istongbu) {
        istongbu = false;
    } else {
        istongbu = true;
    }
    try {
        $.ajax({
            type: mode,
            beforeSend: function (xhr) {
                if (!QueryString("courseId")) {
                    token = strToJson(GetlocalStorage("userinfo_token"), token);
                    xhr.setRequestHeader("X-Session-Token", token.token);
                }
            },
            //手机端需要加上token验证
            headers: {
                //"Accept": "text/plain; charset=utf-8",
                //"Content-Type": "text/plain; charset=utf-8",
                "Accept": "application/json, text/javascript, */*; charset=utf-8",
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
            },
            async: istongbu,
            url: url,
            data: parm,
            dataType: callBackType,
            cache: false,
            success: function (msg, status, xhr) {
                pedding = false;
                $("#loadingToast").hide();
                msg = strToJson(msg);
                if (msg && msg.errorcode && (msg.errorcode == 35 || msg.errorcode == 36)) {
                    alert("身份验证已失效，请重新登录！");
                } else {
                    callBack(msg);
                    //  console.log(msg);
                }
            },
            error: function (err) {
                // $.hideIndicator(); //loading
                if (callBackError != undefined && callBackError != null && callBackError != "")
                    callBackError(err);
                // $.alert(err);
                console.log('请求服务器错误！');
                pedding = false;
                console.error("服务器访问异常：" + err.readyState);
                $("#loadingToast").hide();
            }
        });

    }
    catch (error) {
        console.log(error);
        alert("请求错误,请刷新重试！");
        $("#loadingToast").hide();
    }
}
/**
* 工具 || 获得本地存储
*/
function GetlocalStorage(name) {
    // / <summary>
    // / 获得本地数据
    // / </summary>
    if (window.localStorage) {
        var value = localStorage.getItem(name);
        if (value != null) {
            return JSON.parse(value);
        } else {
            return value;
        }
    } else {
        alert("您需要升级浏览器");
    }
}
/**
*工具 || 存储
*/
function SetlocalStorage(name, obj) {
    // / <summary>
    // / 重写本地数据
    // / </summary>
    if (window.localStorage) {
        try {
            localStorage.setItem(name, JSON.stringify(obj));
        }
        catch (oException) {
            if (oException.name == 'QuotaExceededError') {
                console.log('超出本地存储限额！');
                //如果历史信息不重要了，可清空后再设置
                localStorage.clear();
                localStorage.setItem(name, JSON.stringify(obj));
            }
        }
    } else {
        alert("您需要升级浏览器才能够进行学习");
    }
}
//字符转对象
function strToJson(str) {
    try {
        if (str != null && str != "" && str != undefined) {
            return JSON.parse(str);
        } else {
            return null;
        }
    } catch (e) {
        return str;
    }
}
</script>
</body>
</html>